package cn.yuanqiao.archive.storeRoom.service.impl;


import cn.yuanqiao.archive.storeRoom.domain.*;
import cn.yuanqiao.archive.storeRoom.mapper.*;
import cn.yuanqiao.archive.storeRoom.service.TechnicalTreatmentService;

import cn.yuanqiao.common.utils.PageUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author GW
 * @since 2024-04-16
 */
@Slf4j
@Service
public class TechnicalTreatmentServiceImpl implements TechnicalTreatmentService {

    @Autowired
    private TechnicalTreatmentMapper technicalTreatmentMapper;

    @Autowired
    @Lazy
    private TechnicalTreatmentService service;


    @Autowired
    private UpDownLogsMapper upDownLogsMapper;

    @Autowired
    private StoreroomMapper storeroomMapper;

    @Autowired
    private UpDownShelvesMapper upDownShelvesMapper;

    @Autowired
    private DaBoxMapper daBoxMapper;

    @Override
    public int save(TechnicalTreatment technicalTreatment) {
        //1.暂定为批次号不可重复
        try {
            int count = technicalTreatmentMapper.findByCount(technicalTreatment.getBatchNum(), technicalTreatment.getTableName());
            if (count > 0) {
                throw new RuntimeException("批次号重复，添加终止");
            }
        } catch (Exception e) {
            // 处理数据库查询异常，给出明确的错误提示
            throw new RuntimeException("查询批次号重复性时发生错误", e);
        }
        // 调用Mapper层的方法进行保存操作 TODO 不可重复字段
        return technicalTreatmentMapper.save(technicalTreatment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(JSONObject object) {
        List<Long> ids = ((List<String>) object.get("ids")).stream().map(Long::parseLong).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)) {
            throw new RuntimeException("ids不能为空");
        }
        int i = 0;
        try {
            for (Long id : ids) {
                TechnicalTreatment technicalTreatment = new TechnicalTreatment();
                //1.根据此id查询中间表
                List<Long> idList = technicalTreatmentMapper.findById(id, technicalTreatment.getTreatmentYqBoxTableName());
                //2.如果中间表有数据 删除中间表
                if (CollectionUtils.isNotEmpty(idList)) {
                    JSONObject obj = new JSONObject();
                    obj.put("id", id);
                    obj.put("ids", idList.stream().map(String::valueOf).collect(Collectors.toList()));
                    obj.put("status", 1);
                    obj.put("type", "");
                    service.updateStatus(obj);
                    technicalTreatmentMapper.deleteById(idList, id, new TechnicalTreatment().getTreatmentYqBoxTableName());
                }
//                technicalTreatment.setId(id);
            }
            //3.逻辑删除此表
            i = technicalTreatmentMapper.removeById(ids, new TechnicalTreatment().getTableName());
        } catch (Exception e) {
            log.error("删除失败: {}", e.getMessage());
        }
        return i;
    }

    @Override
    @Transactional
    public int updateById(TechnicalTreatment technicalTreatment) {
        //入参校验
        if (technicalTreatment == null) {
            log.error("TechnicalTreatment is null, update operation aborted.");
            throw new IllegalArgumentException("TechnicalTreatment cannot be null.");
        }
        // todo 唯一性字段
        if (technicalTreatment.getTaskStatus() != null && "2".equals(technicalTreatment.getTaskStatus())) {
            technicalTreatment.setTaskStart(new Date());
        }
        if (technicalTreatment.getTaskStatus() != null && "3".equals(technicalTreatment.getTaskStatus())) {
            technicalTreatment.setTaskEnd(new Date());
        }
        technicalTreatment.setUpdateUser(SecurityUtils.getUsername());
        technicalTreatment.setUpdateTime(new Date());
        try {
            if ("3".equals(technicalTreatment.getTaskStatus())) {
                int r = technicalTreatmentMapper.updateByDa(technicalTreatment, new Box().getTableName());
            }
            return technicalTreatmentMapper.updateById(technicalTreatment);
        } catch (Exception e) {
            log.error("Error occurred during update operation: ", e);
            throw new RuntimeException("Update operation failed.", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TechnicalTreatmentVo findById(Long id, String sjType) {
        // 验证输入参数
        if (id == null || sjType == null) {
            throw new IllegalArgumentException("Id and sjType must not be null.");
        }
        TechnicalTreatmentVo vo = technicalTreatmentMapper.findByIdJS(id, new TechnicalTreatment().getTableName());
        if (vo == null) {
            throw new IllegalArgumentException("TechnicalTreatmentVo not found for id: " + id);
        }
        return vo;
    }

    @Override
    public List<UpDownShelves> getDangAnList(Box box) {
        // 输入验证
        if (box == null || box.getSjType() == null) {
            throw new IllegalArgumentException("Box and its sjType must not be null.");
        }
        List<UpDownShelves> upDownShelves = new ArrayList<>();
        String code = Optional.ofNullable(SecurityUtils.getTenantCode())
                .map(String::toUpperCase)
                .orElseThrow(() -> new IllegalStateException("Tenant code must not be null"));
        if ("0".equals(box.getSjType())) {
            upDownShelves = technicalTreatmentMapper.getDangAnListH(box, code);
        }
        if ("1".equals(box.getSjType())) {
            upDownShelves = technicalTreatmentMapper.getDangAnListJ(box, code);
        }
        return upDownShelves;
    }

    @Override
    @Transactional
    public int updateStatus(JSONObject object) {
        List<Long> ids = (List<Long>) object.get("ids");
        Integer status = object.getInteger("status");
        String type = object.getString("type");

        String code = SecurityUtils.getTenantCode().toUpperCase();
        try {
            //0. 档案上下架按钮
            if ("0".equals(type)) {
                String tableName = new Grid().getTableName();
                String boxTableName = new Box().getTableName();
                //todo 已经上架数可能成为负数 待解决
                technicalTreatmentMapper.updateNum(ids, tableName, boxTableName);
            }
            //1.添加至处理单
            if ("1".equals(type)) {
                Long id = object.getLong("id");
                technicalTreatmentMapper.saveByZjb(id, ids, new TechnicalTreatment().getTreatmentYqBoxTableName());
            }
            //2.移除
            if ("2".equals(type)) {
                Long id = object.getLong("id");
                technicalTreatmentMapper.removeByZjb(id, ids, new TechnicalTreatment().getTreatmentYqBoxTableName());
            }
            if (object.containsKey("List")) {
                JSONArray list = object.getJSONArray("List");
                for (int j = 0; j < list.size(); j++) {
                    JSONObject jsonObject = list.getJSONObject(j);
                    String subtableName = jsonObject.getString("tableName");
                    Long daId = jsonObject.getLong("daId");
                    Long kfId = jsonObject.getLong("kfId");

                    if ("0".equals(type)) {
                        ArrayList<Map<String, Object>> hedaidlist = daBoxMapper.getDaIdListByBoxId(daId, code);
                        for (Map map2 : hedaidlist) {
                            String tableName = map2.get("SUB_TABLE_NAME").toString();
                            Long id = Long.parseLong(map2.get("DA_ID").toString());
                            //下架记录
                            Map<String, Object> map1 = upDownShelvesMapper.getDaMessageById(tableName, id);
                            if (map1 == null) {
                                map1 = new HashMap<>();

                            }
                            Storeroom storeroom = storeroomMapper.selectStoreroomByStoreId(kfId, code);
                            UpDownLogs upDownLogs = new UpDownLogs();
                            upDownLogs.setCreator(SecurityUtils.getUserId());
                            upDownLogs.setDaId(id);
                            upDownLogs.setCreateTime(new Date());
                            upDownLogs.setSubTableName(tableName);
                            upDownLogs.setSxjgzry(SecurityUtils.getLoginUser().getSysUser().getNickName());
                            upDownLogs.setSxjrq(new Date());
                            upDownLogs.setType("下架");
                            upDownLogs.setXjyy("档案信息技术处理");
                            upDownLogs.setTitle(map1.get("TITLE") == null ? "" : map1.get("TITLE").toString());
                            upDownLogs.setDh(map1.get("DH") == null ? "" : map1.get("DH").toString());
                            upDownLogs.setStoreCode(storeroom.getStoreCode());
                            upDownLogs.setStoreName(storeroom.getStoreName());
                            upDownLogsMapper.insertUpDownLogs(upDownLogs);
                        }
                    } else {
                        //下架记录
                        Map<String, Object> map1 = upDownShelvesMapper.getDaMessageById(subtableName, daId);
                        if (map1 == null) {
                            map1 = new HashMap<>();

                        }
                        Storeroom storeroom = storeroomMapper.selectStoreroomByStoreId(kfId, code);
                        UpDownLogs upDownLogs = new UpDownLogs();
                        upDownLogs.setCreator(SecurityUtils.getUserId());
                        upDownLogs.setDaId(daId);
                        upDownLogs.setCreateTime(new Date());
                        upDownLogs.setSubTableName(subtableName);
                        upDownLogs.setSxjgzry(SecurityUtils.getLoginUser().getSysUser().getNickName());
                        upDownLogs.setSxjrq(new Date());
                        upDownLogs.setType("下架");
                        upDownLogs.setXjyy("档案信息技术处理");
                        upDownLogs.setTitle(map1.get("TITLE") == null ? "" : map1.get("TITLE").toString());
                        upDownLogs.setDh(map1.get("DH") == null ? "" : map1.get("DH").toString());
                        upDownLogs.setStoreCode(storeroom.getStoreCode());
                        upDownLogs.setStoreName(storeroom.getStoreName());
                        upDownLogsMapper.insertUpDownLogs(upDownLogs);
                    }
                }
            }
            return technicalTreatmentMapper.updateStatus(ids, status, code);
        } catch (Exception e) {
            // 例如，记录日志、回滚事务等
            log.error("Failed to update status", e.getMessage());
        }
        return -1;
    }

    @Override
    public List<TechnicalTreatmentVo> findByPage(TechnicalTreatment technicalTreatment) {
        try {
            List<TechnicalTreatmentVo> result = technicalTreatmentMapper.findByPage(technicalTreatment);
            // 避免返回null，改为返回空列表
            return result != null ? result : Collections.emptyList();
        } catch (Exception e) {
            // 日志记录异常，可以使用Log4j、SLF4J等
            log.error("Error fetching technical treatments by page: {}", e.getMessage());
            // 在这里选择返回空列表作为错误情况的处理
            return Collections.emptyList();
        }
    }

    @Override
    public List<UpDownShelves> findByDa(Long id, String sjType, String taskType) {
        List<Long> byIds;
        try {
            byIds = technicalTreatmentMapper.findById(id, new TechnicalTreatment().getTreatmentYqBoxTableName());
        } catch (Exception e) {
            log.error("Error occurred while finding byIds: {}", e.getMessage());
            // 此处采取的具体行动取决于业务需求
            byIds = Collections.emptyList();
        }
        if (CollectionUtils.isEmpty(byIds)) {
            return Collections.emptyList();
        }
        Box box = new Box();
        box.setBoxIds(byIds);
        box.setSjType(sjType);
        if (StringUtils.isNotEmpty(taskType)) {
            box.setPutawayStatus(Integer.parseInt(taskType));
        }
        // 档案分页查询
        PageUtils.startPage();
        List<UpDownShelves> dangAnList = service.getDangAnList(box);
        return dangAnList;
    }

}
